// lib/providers/reader_providers.dart

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../models/comic_chapter_model.dart';
import '../home/model/comic_detail_model.dart';
import 'chapter_repository.dart';

// 新增：保存当前传入的 ComicDetailModel（整本漫画详情）
final comicDetailProvider = StateProvider<ComicDetailModel?>((ref) => null);

// 从 comicDetail 派生章节元数据列表（ComicChaptersModel）
final comicChaptersProvider = Provider<List<ComicChaptersModel>>((ref) {
  final detail = ref.watch(comicDetailProvider);
  if (detail == null) return [];
  return detail.comicChapters ?? [];
});

// 辅助：根据当前 chapterId 从章节列表中查找下一个 chapterId
String? nextChapterIdFromList(WidgetRef ref, String currentChapterId) {
  final chapters = ref.read(comicChaptersProvider);
  for (int i = 0; i < chapters.length; i++) {
    final c = chapters[i];
    if (c.chapterId == currentChapterId) {
      if (i + 1 < chapters.length) {
        return chapters[i + 1].chapterId;
      } else {
        return null; // 已经是最后一章
      }
    }
  }
  return null;
}

final chapterRepoProvider =
    Provider<ChapterRepository>((ref) => ChapterRepository());

/// 当前正在阅读的章节 id（可以由外层传入 initialId，通过修改该 provider 切换章节）
final currentChapterIdProvider = StateProvider<String?>((ref) => null);

/// 通过 chapterId 获取章节数据
final chapterProvider = FutureProvider.autoDispose
    .family<ComicChapterModel?, String>((ref, chapterId) async {
  final repo = ref.watch(chapterRepoProvider);
  final chapter = await repo.fetchChapterById(chapterId);
  return chapter;
});

/// 阅读器配置：翻页模式（true = vertical / 条漫； false = horizontal page）
final isVerticalScrollProvider = StateProvider<bool>((ref) => true);

/// 当前页索引（0-based）
final currentIndexProvider = StateProvider<int>((ref) => 0);

/// 工具栏显示/隐藏
final toolbarVisibleProvider = StateProvider<bool>((ref) => true);

/// 夜间模式
final nightModeProvider = StateProvider<bool>((ref) => false);

/// 本地记录最后阅读位置（示例：使用 shared_preferences 存储）
final lastReadKeyForComicProvider =
    Provider.family<String, String>((ref, comicId) => 'last_read_$comicId');

final lastReadIndexProvider =
    StateProvider.family<int, String>((ref, comicId) => 0);

/// 保存/加载 last read 的 helper
final readingPersistenceProvider =
    Provider<ReadingPersistence>((ref) => ReadingPersistence());

class ReadingPersistence {
  Future<void> saveLastIndex(String comicId, int index) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt('last_read_$comicId', index);
  }

  Future<int> loadLastIndex(String comicId) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getInt('last_read_$comicId') ?? 0;
  }
}
